import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:sports_new/controller/navigation_logic.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/controller/match/list/zq_end_logic.dart';
import 'package:sports_new/controller/match/list/zq_match_filter_logic.dart';
import 'package:sports_new/controller/match/list/zq_notbegin_logic.dart';
import 'package:sports_new/controller/service/config_service.dart';
import 'package:sports_new/entity/match/zq_list_entity.dart';
import 'package:sports_new/server/api/soccer_api.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/user.dart';

class ZqViewLogic extends GetxController implements MatchListProvider {
  ZqViewLogic(this.type, this.tag, {this.date,this.hotId,this.hotLabel});

  ZqMatchType type;
  String tag;
  DateTime? date;
  String? hotId;
  String? hotLabel;
  final refreshC = EasyRefreshController();

  late ZqMatchFilterLogic filter;
  final scrollC = ApmScrollController();
  //所有比赛
  List<ZqListEntity> originalMatch = [];
  //筛选比赛
  // List<ZqListEntity> filterData = [];
  List<DateTime>? dayList;
  List<List<ZqListEntity>>? groupMatchList;
  List<ZqListEntity> matchList = [];
  bool firstLoad = true;
  //01234 全部 一级 竞足 方案 情报
  QuickFilter quickFilter = QuickFilter.all;
  bool isBottomHide = false;
  // var showTop = false.obs;
  int hideMatchNum = 0;
  bool isScrollDown = false;

  @override
  void onInit() {
    super.onInit();
    if(tag == Constant.matchFilterTagHot) {
      filter = Get.find<ZqMatchFilterLogic>(tag: "$tag$hotLabel");
    }else{
      filter = Get.find<ZqMatchFilterLogic>(tag: tag);
    }
    scrollC.addListener(() {
      if (scrollC.offset < 0 && !isScrollDown) {
        isScrollDown = true;
        update();
      } else if (scrollC.offset > 9 && isScrollDown) {
        isScrollDown = false;
        update();
      }
      Get.find<NavigationLogic>().onMatchPageScroll();
    });
  }

  @override
  updateView() {
    update();
  }

  @override
  void onReady() {
    super.onReady();
    getMatch();
  }

  @override
  Future getMatch() async {
    groupMatchList ??= List.generate(10, (index) => List<ZqListEntity>.generate(10, (index) => ZqListEntity()));
    if(matchList.noValue) {
      matchList = List<ZqListEntity>.generate(10, (index) => ZqListEntity());
    }
    var hotMatchId = hotId??'';
    var hotTeamId = "";
    if(hotId?.contains("-")??false){
      hotMatchId = hotId?.split('-')[0]??'';
      hotTeamId = hotId?.split('-')[1]??'';
    }
    List<ZqListEntity>? result;
    if (type == ZqMatchType.hot){
      result = await SoccerApi.getZqHotList(hotMatchId,teamId: hotTeamId);
    }else if (type == ZqMatchType.all) {
      result = await SoccerApi.getZqAllList();
    } else if (type == ZqMatchType.begin) {
      result = await SoccerApi.getZqMatchBeginList();
    } else if (type == ZqMatchType.schedule) {
      result = await SoccerApi.getZqMatchScheduleList(
          DateTimeUtils.formatDateTime(date!, 'yyyy-MM-dd'));
    } else if (type == ZqMatchType.end) {
      result = await SoccerApi.getZqMatchResultList(
          DateTimeUtils.formatDateTime(date!, 'yyyy-MM-dd'));
    } else if (type == ZqMatchType.focus) {
      if (!User.isLogin) {
        return;
      }
      result = await SoccerApi.getZqMatchFocus();
    }

    if (result != null) {
      originalMatch = result;
      if (firstLoad) {
        filter.initLeague(type);
        quickFilter = filter.quickFilter;
      }
      filterMatch(filter.getHideLeagueIdList());
      firstLoad = false;
      update();
    }
  }

  void filterMatch(List<int> hideLeagueId) {
    isBottomHide = false;
    List<ZqListEntity> matchListTemp = [];
    hideMatchNum = 0;
    for (var match in originalMatch) {
      if (quickFilter == QuickFilter.qingbao && match.intelligence == 0) {
        hideMatchNum++;
        continue;
      }
      if(quickFilter == QuickFilter.guandian && match.planCnt == 0){
        hideMatchNum++;
        continue;
      }
      if (!hideLeagueId.contains(match.leagueId)) {
        if (filter.leagueType == ZqFilterType.jz) {
          if(match.jcMatchNo != null) {
            matchListTemp.add(match);
          }
        } else if (filter.leagueType == ZqFilterType.dc) {
          if(match.dcMatchNo != null) {
            matchListTemp.add(match);
          }
        } else if (filter.leagueType == ZqFilterType.ssc) {
          if(match.sfcMatchNo != null) {
            matchListTemp.add(match);
          }
        }
        else {
          matchListTemp.add(match);
        }
      }
    }
    if (quickFilter == QuickFilter.yiji ||
        quickFilter == QuickFilter.jingcai ||
        quickFilter == QuickFilter.all) {
      hideMatchNum = filter.hideMatchNum;
    }
    if (type == ZqMatchType.schedule || type == ZqMatchType.end) {
      if (matchListTemp.isNotEmpty) {
        matchListTemp.first.needTopSpace = true;
      }
      matchList = matchListTemp;
      if (type == ZqMatchType.schedule) {
        Get.find<ZqNotBeginLogic>().hideMatchNum = hideMatchNum;
        Get.find<ZqNotBeginLogic>().onShowBottom();
      } else {
        Get.find<ZqEndLogic>().hideMatchNum = hideMatchNum;
        Get.find<ZqEndLogic>().onShowBottom();
      }
      update();
    } else {
      groupData(matchListTemp);
    }
  }

  void groupData(List<ZqListEntity> matchList) {
    List<DateTime> dateListTemp = [];
    List<List<ZqListEntity>> groupMatchListTemp = [];
    //同一天比赛
    List<ZqListEntity> sameDayMatchList = [];
    List<ZqListEntity> endMatchList = [];
    bool hasEnd = false;
    bool hasError = false;
    for (int i = 0; i < matchList.length; i++) {
      ZqListEntity match = matchList[i];
      final dateTime = DateTime.parse(match.matchTime!);
      if (dateListTemp.isEmpty) {
        if((type == ZqMatchType.hot || type == ZqMatchType.focus) && match.hasEnd){
          endMatchList.add(match);
          hasEnd = true;
        }else{
          dateListTemp.add(dateTime);
          sameDayMatchList.add(match);
        }
      } else if (DateUtils.isSameDay(dateListTemp.last, dateTime)) {
        sameDayMatchList.add(match);
      } else {
        sameDayMatchList.last.lastMatchInDay = true;
        groupMatchListTemp.add(sameDayMatchList);
        dateListTemp.add(dateTime);
        sameDayMatchList = [match];
      }
    }
    //加上最后一天比赛
    if (sameDayMatchList.isNotEmpty) {
      sameDayMatchList.last.lastMatchInDay = true;
      groupMatchListTemp.add(sameDayMatchList);
    }
    if(hasEnd){
      dateListTemp.add(DateTime(1999));
      groupMatchListTemp.add(endMatchList.reversed.toList());
      if(groupMatchListTemp.length > 1) {
        groupMatchListTemp[groupMatchListTemp.length - 2].last.lastMatchInDay = true;
      }
    }

    dayList = dateListTemp;
    groupMatchList = groupMatchListTemp;
    update();
  }

  onSelectMatchType(QuickFilter filterType, {bool fromFilterPage = false}) {
    quickFilter = filterType;
    if (Get.find<ConfigService>().zqConfig.zqAlert7 == 1) {
      try {
        Get.find<ZqViewLogic>(tag: Constant.matchFilterTagAll)
            .filterMatchByType(filterType,fromFilterPage);
      } catch (e) {}
      if(type != ZqMatchType.hot){
        try {
          Get.find<ZqViewLogic>(tag: "${Constant.matchFilterTagHot}$hotLabel")
              .filterMatchByType(filterType,fromFilterPage);
        } catch (e) {}
      }
      if (type != ZqMatchType.begin) {
        try {
          Get.find<ZqViewLogic>(tag: Constant.matchFilterTagBegin)
              .filterMatchByType(filterType,fromFilterPage);
        } catch (e) {}
      }
      if (type != ZqMatchType.schedule) {
        try {
          final logic = Get.find<ZqNotBeginLogic>();
          logic.quickFilter = filterType;
          Get.find<ZqViewLogic>(
                  tag: '${Constant.matchFilterTagSchedule}${logic.index}')
              .filterMatchByType(filterType,fromFilterPage);
        } catch (e) {}
      }
      if (type != ZqMatchType.end) {
        try {
          final logic = Get.find<ZqEndLogic>();
          logic.quickFilter = filterType;
          Get.find<ZqViewLogic>(
                  tag: '${Constant.matchFilterTagResult}${logic.index}')
              .filterMatchByType(filterType,fromFilterPage);
        } catch (e) {}
      }
    }
    if (!fromFilterPage) {
      filterMatchByType(filterType,fromFilterPage);
    }
  }

  filterMatchByType(QuickFilter filterType,bool fromFilterPage) {
    quickFilter = filterType;
    switch(quickFilter){
      case QuickFilter.all:
        onSelectDefaultMatch(fromFilterPage: fromFilterPage);
        break;
      case QuickFilter.yiji:
        filter.leagueType = ZqFilterType.all;
        filter.onSelectOneLevel();
        filterMatch(filter.getHideLeagueIdList());
        break;
      case QuickFilter.jingcai:
        filter.onSelectFilterType(ZqFilterType.jz);
        filterMatch(filter.getHideLeagueIdList());
        break;
      case QuickFilter.guandian:case QuickFilter.qingbao:
        onSelectDefaultMatch(fromFilterPage: fromFilterPage,type: quickFilter);
        break;
    }
    filter.savaFilterToLocal();
  }

  void onSelectDefaultMatch({QuickFilter type = QuickFilter.all,bool fromFilterPage = false}) {
    quickFilter = type;
    if(!fromFilterPage) {
      filter.leagueType = ZqFilterType.all;
    }
    filter.onSelectAll();
    filter.updateLeague();
    filterMatch([]);
    filter.savaFilterToLocal();
  }

  void onCloseBottomBar() {
    isBottomHide = true;
    update();
  }

  @override
  Future doRefresh() async {
    if(refreshC.headerState?.mode.isIdle == false) return;
    refreshC.callRefresh();
    // update();
  }

  @override
  String getTicketName(ZqListEntity match) {
    String name = '';
    if (filter.leagueType == ZqFilterType.jz) {
      name = match.jcMatchNo ?? '';
    } else if (filter.leagueType == ZqFilterType.dc) {
      name = match.dcMatchNo ?? '';
    } else if (filter.leagueType == ZqFilterType.ssc) {
      name = match.sfcMatchNo ?? '';
    } else {
      name = ((match.jcMatchNo ?? match.dcMatchNo) ?? match.sfcMatchNo) ?? '';
    }
    return name;
  }
}
